package server.response;


import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import server.constant.HttpContentType;
import server.resolver.resource.DefaultResourceResolver;
import server.resolver.suffix.SuffixResolver;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cg
 * @date 2023/6/7 13:38
 */
public class HttpResponse {
    private ChannelHandlerContext ctx;
    private HttpObject request;

    private Map<String, String> cookieMap = new HashMap<>();

    public HttpResponse(ChannelHandlerContext ctx, HttpObject msg) {
        this.ctx = ctx;
        this.request = msg;
    }

    /**
     * 采用默认的请求头实时发送响应数据
     * @param text 响应数据
     * @throws IOException
     */
    public void writeAndFlush(String text) {
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,
                Unpooled.copiedBuffer(text, CharsetUtil.UTF_8));
        //设置响应类型
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
        //设置响应长度
        response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
        response.headers().set(HttpHeaderNames.SET_COOKIE, getCookies());

        ctx.writeAndFlush(response);

    }

    public void write404() {
        this.writeAndFlush("<h1>404 not found</h1>");
    }

    public void write500() {
        this.writeAndFlush("<h1>500 Exception</h1>");
    }
    /**
     * 返回请求静态资源
     * @param url 请求路径
     */
    public void writeResource(String url) throws IOException {
        //获取文件真实路径
        String path = this.getClass().getResource("/").getPath() + url;
        //判断是否存在该文件
        File file = new File(path);
        if (file.exists() && file.isFile()) {
            String suffix = path.substring(path.lastIndexOf('.'));
            //解析文件
            DefaultResourceResolver defaultResourceResolver = DefaultResourceResolver.getInstance();
            defaultResourceResolver.resolve(file, this, SuffixResolver.suffixResolver(suffix));
        }else {
            write404();
        }
    }

    public void setCookie(String key, String value) {
        this.cookieMap.put(key, value);
    }

    public void removeCookie(String key) {
        this.cookieMap.remove(key);
    }

    private String getCookies() {
        if (cookieMap.isEmpty()) {
            return "";
        }
        StringBuilder res = new StringBuilder();
        for (String key : cookieMap.keySet()) {
            res.append(key).append("=").append(cookieMap.get(key)).append(";");
        }
        return res.substring(0, res.length() - 1);
    }

    public ChannelHandlerContext getCtx() {
        return ctx;
    }

    public void setCtx(ChannelHandlerContext ctx) {
        this.ctx = ctx;
    }
}
